/**
 * @description: aph分析法
 */

export type Matrix = number[][]

/**
 * aph分析法计算权重
 * @params {Array} matrix 矩阵
 * @returns {Array} weightVector 权重向量
 */
export const ahpWeight = (matrix: Matrix): number[] => {
  const n = matrix.length
  const columnSum: number[] = Array(n).fill(0)

  // 计算每列的和
  for (let j = 0; j < n; j++) {
    for (let i = 0; i < n; i++) {
      columnSum[j] += matrix[i][j]
    }
  }

  // 归一化判断矩阵
  const normalizedMatrix: Matrix = []
  for (let i = 0; i < n; i++) {
    normalizedMatrix[i] = []
    for (let j = 0; j < n; j++) {
      normalizedMatrix[i][j] = matrix[i][j] / columnSum[j]
    }
  }

  // 计算权重向量
  const weightVector: number[] = Array(n).fill(0)
  for (let i = 0; i < n; i++) {
    let sum = 0
    for (let j = 0; j < n; j++) {
      sum += normalizedMatrix[i][j]
    }
    weightVector[i] = sum / n
  }

  return weightVector
}

export function consistencyCheck(
  matrix: Matrix,
  weightVector: number[]
): { CI: number; CR: number; lambdaMax: number; result: boolean } {
  const n = matrix.length
  const lambdaMax =
    weightVector.reduce((acc, val, i) => {
      const rowSum = matrix[i].reduce((rowAcc, cell, j) => rowAcc + cell * weightVector[j], 0)
      return acc + rowSum / val
    }, 0) / n

  const CI = (lambdaMax - n) / (n - 1)
  const RI = [0, 0, 0.58, 0.9, 1.12, 1.24, 1.32, 1.41, 1.45, 1.49] // RI值表，对于不同大小的判断矩阵

  const CR = CI / RI[n]

  let result = false
  if (CR < 0.1) {
    // 矩阵具有一致性
    result = true
  } else {
    // 矩阵不具有一致性，需要调整
    result = false
  }
  console.log('一致性指标CI:', CI)
  console.log('一致性比率CR:', CR)
  console.log('最大特征值λ_max:', lambdaMax)
  return { CI, CR, lambdaMax, result }
}
